package com.hwg.shiliupro.controller;

import com.hwg.shiliupro.finals.Code;
import com.hwg.shiliupro.po.R;
import com.hwg.shiliupro.po.SessionList;
import com.hwg.shiliupro.po.User;
import com.hwg.shiliupro.service.SessionListService;
import com.hwg.shiliupro.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/sessions")
public class SessionController {
    @Autowired
    private UserService userService;

    @Autowired
    private SessionListService sessionListService;

    /**
     * 已建立会话
     *
     * @param userId userId
     * @return {@link R}
     */
    @GetMapping("/{userId}")
    public R sessionListAlready(@PathVariable Integer userId){
        List<SessionList> sessionLists = sessionListService.selectByUserId(userId);
        return R.ok().code(Code.GET_OK).data(sessionLists);
    }

    /**
     * 可建立会话的用户
     *
     * @param userId 用户id
     * @return {@link R}
     */
    @GetMapping("/can/{userId}")
    public R canSessionList(@PathVariable Integer userId){
        List<Integer> toUserIds = sessionListService.selectToUserIdByFromUserId(userId);
        toUserIds.add(userId);
        List<User> cloundList = new ArrayList<>();
        for (Integer toUserId : toUserIds) {
            User user = userService.selectById(toUserId);
            cloundList.add(user);
        }
        return R.ok().code(Code.GET_OK).data(cloundList);
    }

    /**
     * 创建会话
     */
    @GetMapping("/createSession")
    public R createSession(@RequestParam Integer userId,@RequestParam Integer toUserId,@RequestParam String toUserName){
        SessionList sessionList = new SessionList();
        sessionList.setUserId(userId);
        sessionList.setUnReadCount(0);
        sessionList.setListName(toUserName);
        sessionList.setToUserId(toUserId);
        sessionListService.insert(sessionList);
        // 对方和我是否建立了会话 没有也要建立会话
        //是否反了
        Integer integer = sessionListService.selectByUserIdAndToUserId(toUserId,userId);
        if(integer == null || integer <= 0){
            User user = userService.selectById(userId);
            sessionList.setUserId(toUserId);
            sessionList.setToUserId(userId);
            sessionList.setListName(user.getName());
            sessionListService.insert(sessionList);
        }
        return R.ok().code(Code.SAVE_OK);
    }

    /**
     * 删除会话
     *
     * @param sessionId 会话id
     * @return {@link R}
     */
    @DeleteMapping("/{sessionId}")
    public R deleteSession(@PathVariable Integer sessionId){
        sessionListService.deleteById(sessionId);
        return R.ok().code(Code.DELETE_OK);
    }
}
